package cn.autumnorange.app.common.rpc.exception;

import cn.autumnorange.app.common.dto.ResultDto;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JsonExceptionImpl implements JsonException {
  public void jsonException(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Exception e,
      int status)
      throws IOException {
    httpServletResponse.setContentType("application/json;charset=UTF-8");
    String errorMsg = "";
    if (e != null) {
      errorMsg = e.getMessage();
      if (e.getCause() != null) {
        errorMsg += " " + e.getCause().getMessage();
      }
    }
    httpServletResponse
        .getWriter()
        .println(
            JSON.toJSONString(
                ResultDto.createResult(
                    status,
                    null,
                    errorMsg,
                    httpServletRequest.getRequestURL().toString(),
                    null,
                    HttpStatus.valueOf(status).getReasonPhrase())));
    //        httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value(),
    // HttpStatus.UNAUTHORIZED.getReasonPhrase());
  }
}
